<?php

declare(strict_types=1);

namespace App\Controller;

use Carbon\Carbon;
use Hyperf\Apidog\Annotation\ApiController;
use Hyperf\Apidog\Annotation\FormData;
use Hyperf\Apidog\Annotation\GetApi;
use Hyperf\Apidog\Annotation\Path;
use Hyperf\Apidog\Annotation\PostApi;
use Hyperf\Apidog\Annotation\PutApi;
use Hyperf\Apidog\Annotation\Query;
use Hyperf\Utils\Arr;
use Hyperf\Context\Context;
use App\Model\AdminMenu;
use App\Model\AdminRole;
use App\Model\AdminUser;

/**
 * @ApiController(prefix="admin/users", tag="系统用户管理", server="backend-api")
 */
class AdminUsersController extends AdminController
{
    /**
     * @GetApi(path="", description="列表")
     * @Query(key="username|账号", rule="")
     * @Query(key="name|名称", rule="")
     * @Query(key="phone_number|手机号", rule="")
     * @Query(key="email|邮箱", rule="email|nullable")
     * @Query(key="role_id|角色", rule="integer")
     * @Query(key="status|状态", rule="boolean")
     * @Query(key="page|页码", rule="integer|min:1")
     * @Query(key="per_page|x条/页", rule="integer|max:100000")
     */
    public function index()
    {
        $validator_data = Context::get('validator.data');
        $AdminUser = AdminUser::query()->with('adminRole:id,role_name')->with('operator:id,name');

        ($username = Arr::get($validator_data, 'username', '')) &&
        $AdminUser->where(function ($query) use ($username) {
            $query->where('username', $username);
        });

        ($name = Arr::get($validator_data, 'name', '')) &&
        $AdminUser->where(function ($query) use ($name) {
            $query->where('name', $name);
        });

        ($phone_number = Arr::get($validator_data, 'phone_number', '')) &&
        $AdminUser->where(function ($query) use ($phone_number) {
            $query->where('phone_number', $phone_number);
        });

        ($email = Arr::get($validator_data, 'email', '')) &&
        $AdminUser->where(function ($query) use ($email) {
            $query->where('email', $email);
        });

        ($role_id = Arr::get($validator_data, 'role_id', 0)) &&
        $AdminUser->where(function ($query) use ($role_id) {
            $query->where('role_id', $role_id);
        });

        (!is_null($user_status = Arr::get($validator_data, 'user_status', null))) &&
        $AdminUser->where(function ($query) use ($user_status) {
            $query->where('user_status', $user_status);
        });

        $data = $AdminUser->orderByDesc('id')->paginate((int)$this->request->input('per_page', 10))->toArray();

        $data['role_options'] = Arr::prepend(AdminRole::all(['id', 'role_name'])->toArray(), ['id' => 0, 'role_name' => '全部']);
        return $this->adminResponse(200, '请求成功', $data);
    }

    /**
     * @GetApi(path="{id:\d+}", description="查看")
     * @Path(key="id|管理员ID", rule="required|integer|exists:admin_users")
     */
    public function show()
    {
        $data = [
            'admin_user' => AdminUser::find($this->request->route('id'))->toArray(),
        ];
        $data = Arr::merge($data, $this->buildOptions());
        return $this->adminResponse(200, '请求成功', $data);
    }

    /**
     * @PutApi(path="{id:\d+}", description="编辑")
     * @Path(key="id|管理员ID", rule="required|integer|exists:admin_users")
     * @FormData(key="phone_number|手机号", rule="string|nullable")
     * @FormData(key="email|邮箱", rule="email|nullable")
     * @FormData(key="role_id|角色", rule="integer|nullable|exists:admin_roles,id")
     * @FormData(key="password|密码，32位md5加密", rule="string|size:32")
     * @FormData(key="menu_permissions|权限菜单", rule="array|nullable")
     */
    public function update()
    {
        return $this->save();
    }

    /**
     * @GetApi(path="options", description="选项")
     */
    public function options()
    {
        return $this->adminResponse(200, '请求成功', $this->buildOptions());
    }

    /**
     * 构建选项
     * @return array
     */
    protected function buildOptions()
    {
        return [
            'role_options' => Arr::prepend(AdminRole::all(['id', 'role_name', 'menu_permissions'])->toArray(), ['id' => null, 'role_name' => '请选择', 'menu_permissions' => []]),
            'menu_tree' => AdminMenu::buildTree(),
        ];
    }

    /**
     * @PostApi(path="", description="添加")
     * @FormData(key="username|账号", rule="required|unique:admin_users")
     * @FormData(key="name|名称", rule="required")
     * @FormData(key="phone_number|手机号", rule="string|nullable")
     * @FormData(key="email|邮箱", rule="email|nullable")
     * @FormData(key="role_id|角色", rule="integer|nullable|exists:admin_roles,id")
     * @FormData(key="password|密码，32位md5加密", rule="required|string|size:32")
     * @FormData(key="menu_permissions|权限菜单", rule="array|nullable")
     */
    public function store()
    {
        return $this->save();
    }

    /**
     * @PutApi(path="{id:\d+}/status", description="更改状态")
     * @Path(key="id|管理员ID", rule="required|integer|exists:admin_users")
     * @FormData(key="user_status|状态（布尔型或0和1）", rule="required|boolean")
     */
    public function updateUserStatus()
    {
        return $this->save();
    }

    /**
     * 保存
     * @return mixed
     */
    protected function save()
    {
        $validator_data = Context::get('validator.data');
        $validator_data['operator_id'] = $this->auth->id();
        Arr::has($validator_data, 'password') && $validator_data['password'] === '' && Arr::forget($validator_data, 'password');
        $AdminUser = Arr::has($validator_data, 'id') ? AdminUser::find(Arr::get($validator_data, 'id')) : new AdminUser();
        if ($AdminUser->forceFill($validator_data)->isDirty()) {
            $AdminUser->updated_at = Carbon::now();
        }
        $AdminUser->save();
        Arr::has($validator_data, 'id') && $AdminUser->deleteCache();
        return $this->adminResponse(200, '请求成功', $AdminUser->toArray());
    }
}
